/**
*@Author      ：anlzou
*@Date        ：21:01 2021/4/23
*@Github      ：https://github.com/anlzou
*@Description ：
*/
package com.anlzou.goods;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 生产者消费者问题
 */
public class SyncLinkedBlockingQueueGoods {
    // 定义一个阻塞队列用来存储生产出来的商品
    private LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();

    // 定义生产商品个数
    private static final int size = 10;

    // 定义启动线程的标志，为0时，启动生产商品的线程；为1时，启动消费商品的线程
    private int flag = 0;

    // 内部类
    public class LinkBlockThread implements Runnable {

        public void run() {
            int new_flag = flag++;
            System.out.println("启动线程 " + new_flag);

            if (new_flag == 0) {
                for (int i = 0; i < size; i++) {
                    int b = new Random().nextInt(255);
                    System.out.println("生产商品：" + b + "号");

                    try {
                        queue.put(b);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("仓库中还有商品：" + queue.size() + "个");

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                for (int i = 0; i < size / 2; i++) {
                    try {
                        int n = queue.take();
                        System.out.println("消费者买去了" + n + "号商品");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("仓库中还有商品：" + queue.size() + "个");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}
